package com.varteq.progress.server.io;

import com.varteq.progress.server.Progress;

public final class DefaultProgressListener implements IProgressListener {
	private double _percentage = -1;
	private double _shift;
	private double _factor;
	private String _progressDescriptionTemplate;
	private Progress _progress;

	public DefaultProgressListener(String progressDescriptionTemplate, double shift, double factor, Progress progress) {
		_progressDescriptionTemplate = progressDescriptionTemplate;
		_shift = shift;
		_factor = factor;
		_progress = progress;
	}

	@Override
	public void update(long bytesRead, long totalBytes, int items) {
		// try {
		// Thread.sleep(10);
		// } catch (InterruptedException e) {
		// e.printStackTrace();
		// }

		double percentage = _shift + _factor * (double) bytesRead / (double) totalBytes;

		if (_percentage == percentage) {
			return;
		}

		_percentage = percentage;
		String description = String.format(_progressDescriptionTemplate, percentage);
		_progress.addEvent(description, percentage, false, null);
	}
}
